// Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

frappe.ui.form.on('Payment Entry', {
	refresh: function(frm) {
        if (frm.is_new() && frm.doc.references.length 
            && in_list(['Purchase Order', 'Sales Order'], frm.doc.references[0].reference_doctype)
        ){
            frappe.call({
                method: "zelin_am.api.get_advance_payment_info",
                args: {
                    reference_doctype: frm.doc.references[0].reference_doctype,
                    reference_name: frm.doc.references[0].reference_name,
                    outstanding: frm.doc.references[0].outstanding_amount
                },
                callback: function(r) {
                    if(!r.exc) {
                        if(r.message) {
                            const [account, paid_amount] = r.message;
                            const field = frm.doc.references[0].reference_doctype == 'Sales Order'? 'paid_from' : "paid_to";
                            if (account){
                                frm.set_value(field, account);
                                refresh_field(field);
                            }
                            if (paid_amount){
                                frm.set_value('paid_amount', paid_amount);
                                refresh_field('paid_amount');
                            }
                        }
                    }
                }
            });
        }
	}
})